<template>
  <div v-if="show" class="modal-overlay">
    <div class="modal-content">
      <div class="modal-header">
        <h3>新增库存项</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <form @submit.prevent="handleSubmit">
          <div class="form-row">
            <div class="form-group">
              <label for="itemType">库存项类型</label>
              <select 
                id="itemType" 
                v-model="formData.type"
                class="form-control"
                :class="{ 'error': showError && formData.type===null }"
              >
                <option :value="null" disabled>请选择库存项类型</option>
                <option :value="InventoryItemType.CHEMICAL">化学试剂</option>
                <option :value="InventoryItemType.ELECTRONIC">电子元器件</option>
                <option :value="InventoryItemType.OTHER">其他</option>
              </select>
              <div class="error-message" v-if="showError && formData.type===null">
                请选择库存项类型
              </div>
            </div>
            <div class="form-group">
              <label for="unit">库存单位</label>
              <input 
                id="unit" 
                v-model="formData.unit" 
                type="text" 
                class="form-control"
                :class="{ 'error': showError && !formData.unit }"
                :placeholder="getSpecsPlaceholder()"
              >
              <div class="error-message" v-if="showError && !formData.unit">
                请输入单位
              </div>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="casNo">CAS编号</label>
              <input 
                id="casNo" 
                v-model="formData.casNo" 
                type="text" 
                class="form-control"
                :class="{ 'error': showError && formData.type === InventoryItemType.CHEMICAL && !formData.casNo }"
                :disabled="formData.type !== InventoryItemType.CHEMICAL"
                placeholder="110-54-3"
              >
              <div class="error-message" v-if="showError && formData.type === InventoryItemType.CHEMICAL && !formData.casNo">
                请输入CAS编号
              </div>
            </div>
            <div class="form-group">
              <label for="stockNum">库存数量</label>
              <input 
                id="stockNum" 
                v-model="formData.stockNum" 
                type="text" 
                class="form-control"
                :class="{ 'error': showError && (formData.stockNum === null || formData.stockNum === undefined) }"
                placeholder="2"
                min="0"
              >
              <div class="error-message" v-if="showError && (formData.stockNum === null || formData.stockNum === undefined)">
                请输入库存数量
              </div>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="itemName">名称</label>
              <input 
                id="itemName" 
                v-model="formData.name" 
                type="text" 
                class="form-control"
                :class="{ 'error': showError && !formData.name }"
                :placeholder="getNamePlaceholder()"
              >
              <div class="error-message" v-if="showError && !formData.name">
                请输入名称
              </div>
            </div>
            <div class="form-group">
              <label for="location">存储地点</label>
              <input 
                id="location" 
                v-model="formData.location" 
                type="text" 
                class="form-control"
                :class="{ 'error': showError && !formData.location }"
                placeholder="试剂柜第1层"
              >
              <div class="error-message" v-if="showError && !formData.location">
                请输入存储地点
              </div>
            </div>
            
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="purity">型号/纯度</label>
              <input 
                id="purity" 
                v-model="formData.purity" 
                type="text" 
                class="form-control"
                :placeholder="getpurityPlaceholder()"
              >
              <div class="error-message" v-if="showError && !formData.purity">
                请输入型号/纯度
              </div>
            </div>
            <div class="form-group">
              <label for="expirationDate">到期时间</label>
              <input 
                id="expirationDate" 
                v-model="formData.expirationDate" 
                type="datetime-local" 
                class="form-control"
                :placeholder="formData.type === InventoryItemType.CHEMICAL ? '2022-01-01T00:00:00' : '可选'"
              >
            </div>                     
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="brand">品牌</label>
              <input 
                id="brand" 
                v-model="formData.brand" 
                type="text" 
                class="form-control"
                :placeholder="getBrandPlaceholder()"
              >
              <div class="error-message" v-if="showError && !formData.brand">
                请输入品牌
              </div>
            </div>
            <div class="form-group">
              <label for="subject">课题组</label>
              <input 
                id="subject" 
                v-model="formData.subject" 
                type="text" 
                class="form-control"
                placeholder="EFD"
              >
            </div>
            
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="catalogNumber">货号</label>
              <input 
                id="catalogNumber" 
                v-model="formData.catalogNumber" 
                type="text" 
                class="form-control"
                placeholder='N431444-1L'
              >
            </div>          
            
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button class="cancel-btn" @click="handleClose">取消</button>
        <button 
          class="submit-btn" 
          @click="handleSubmit"
          :disabled="isSubmitting"
        >
          {{ isSubmitting ? '提交中...' : '提交' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch,onMounted } from 'vue';
import { InventoryItemType, type CreateInventoryItemRequest } from '../../types/inventory';

// 定义props
const props = defineProps<{
  show: boolean;
  labId: string;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'submit', data: CreateInventoryItemRequest): void;
}>();

// 表单数据
const formData = reactive<CreateInventoryItemRequest>({
  name: '',
  type: null as unknown as InventoryItemType, // 初始值设为null，强制用户选择
  casNo: '',
  purity: '',
  brand: '',
  catalogNumber: '',
  specs: '',
  unit: '',
  stockNum: '0',
  location: '',
  expirationDate: '',
  researchGroupId: props.labId,
  subject: ''
});

// 从localStorage获取用户信息并设置researchGroupId
onMounted(() => {
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    const parsedInfo = JSON.parse(userInfo);
    if (parsedInfo.researchGroupId) {
      formData.researchGroupId = parsedInfo.researchGroupId;
    }
  }
});

// 监听labId变化，更新表单数据
watch(() => props.labId, (newLabId) => {
  if (newLabId) {
    formData.researchGroupId = newLabId;
  }
});

const isSubmitting = ref(false);
const showError = ref(false);

// 关闭模态框
const handleClose = () => {
  resetForm();
  emit('close');
};

// 重置表单
const resetForm = () => {
  formData.name = '';
  formData.type = null as unknown as InventoryItemType; // 重置为null，强制用户重新选择
  formData.casNo = '';
  formData.purity = '';
  formData.brand = '';
  formData.catalogNumber = '';
  formData.specs = '';
  formData.unit = '';
  formData.stockNum = '0';
  formData.location = '';
  formData.expirationDate = '';
  formData.subject = '';
  showError.value = false;
};

const getpurityPlaceholder = () => {
  switch (formData.type) {
    case InventoryItemType.ELECTRONIC:
      return '中号';
    case InventoryItemType.OTHER:
      return '中号';
    case InventoryItemType.CHEMICAL:
      return '0.9';
    default:
      return '0.9';
    }
};

// 根据选择的库存项类型获取名称输入框的placeholder
const getNamePlaceholder = () => {
  switch (formData.type) {
    case InventoryItemType.ELECTRONIC:
      return '铁钉29';
    case InventoryItemType.OTHER:
      return '苹果';
    case InventoryItemType.CHEMICAL:
    default:
      return '正己烷';
  }
};

// 根据选择的库存项类型获取品牌输入框的placeholder
const getBrandPlaceholder = () => {
  switch (formData.type) {
    case InventoryItemType.ELECTRONIC:
      return '铁钉大方';
    case InventoryItemType.OTHER:
      return '富士';
    case InventoryItemType.CHEMICAL:
    default:
      return '西陇';
  }
};

// 根据选择的库存项类型获取规格输入框的placeholder
const getSpecsPlaceholder = () => {
  switch (formData.type) {
    case InventoryItemType.ELECTRONIC:
    case InventoryItemType.OTHER:
      return '个';
    case InventoryItemType.CHEMICAL:
    default:
      return 'L';
  }
};

// 提交表单
const handleSubmit = async () => {
  // 显示验证错误
  showError.value = true;
  
  // 验证表单
  if (!formData.name || !formData.unit || formData.stockNum === null || formData.stockNum === undefined || !formData.location) {
    return;
  }
  
  // 如果是化学试剂，CAS编号不能为空
  if (formData.type === InventoryItemType.CHEMICAL && !formData.casNo) {
    return;
  }

  isSubmitting.value = true;
  try {
    // 创建一个表单数据的副本
    const formDataToSubmit = { ...formData };
    
    // 确保日期格式符合后端 LocalDateTime 要求
    if (formDataToSubmit.expirationDate) {
      // datetime-local 输入已包含时间部分，无需额外处理
      // 确保格式符合后端要求
      formDataToSubmit.expirationDate = formDataToSubmit.expirationDate.replace(' ', 'T');
    }
    
    // 触发提交事件
    emit('submit', formDataToSubmit);
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 700px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  background: white;
  z-index: 1;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 24px;
}

.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  flex: 1;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.form-control:focus {
  border-color: #40a9ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-control.error {
  border-color: #ff4d4f;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  position: sticky;
  bottom: 0;
  background: white;
  z-index: 1;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background: white;
  border: 1px solid #d9d9d9;
  color: #666;
}

.cancel-btn:hover {
  color: #40a9ff;
  border-color: #40a9ff;
}

.submit-btn {
  background: #1890ff;
  border: none;
  color: white;
}

.submit-btn:hover {
  background: #40a9ff;
}

.submit-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 8px;
  }
}
</style>